package cn.ffcs.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

@Data
@Slf4j
@Component
public class FtpProcessor {

    @Resource
    FtpClientPool ftpClientPool;

    public boolean uploadToFtp(String remotePath, String fileName, InputStream fileInputStream) throws Exception {
        boolean upload = true;
        FTPClient ftpClient = null;
        try {
            ftpClient = ftpClientPool.borrowObject();
            ftpClient.changeWorkingDirectory(remotePath);
            //上传文件 参数：上传后的文件名，输入流
            upload = ftpClient.storeFile(fileName, fileInputStream);
        } catch (Exception e) {
            log.error("上传文件异常", e);
            upload = false;
        } finally {
            ftpClientPool.returnObject(ftpClient);
        }
        return upload;
    }

    public boolean uploadFileList(String remotePath, List<File> fileList) throws Exception {
        boolean upload=true;
        FileInputStream fileInputStream = null;
        FTPClient ftpClient = null;
        try {
            ftpClient = ftpClientPool.borrowObject();
            ftpClient.changeWorkingDirectory(remotePath);
            //上传文件 参数：上传后的文件名，输入流
            for (File fileItem:fileList) {
                fileInputStream = new FileInputStream(fileItem);
                ftpClient.storeFile(fileItem.getName() ,fileInputStream);
            }
        } catch (Exception e) {
            log.error("上传文件异常", e);
            upload = false;
        } finally {
            ftpClientPool.returnObject(ftpClient);
        }
        return upload;
    }
}
